/*
 * Copyright (C) 2010 TopCoder Inc., All Rights Reserved.
 */
package com.hercules.android.receiver.commands;

import java.util.HashMap;

import org.json.JSONObject;

import android.os.Handler;

import com.hercules.android.receiver.Config;
import com.hercules.android.receiver.Receiver;
import com.hercules.android.receiver.entities.XREApplication;
import com.hercules.android.receiver.entities.XREObject;
import com.hercules.android.receiver.entities.XREView;

/**
 * <p>
 * This command handler class will handle the CONNECT command.
 * </p>
 * 
 * @author TCSASSEMBER
 * @version 1.0
 */
public class XREConnectCommandHandler extends XRECommandHandler {
    /**
     * Create a new <code>XREConnectCommandHandler</code> with the <code>Receiver</code> instance.
     * 
     * @param receiver
     *            the <code>Receiver</code> instance.
     * @throws IllegalArgumentException
     *             if argument is null
     */
    public XREConnectCommandHandler(Receiver receiver) {
        super(receiver);
    }

    /**
     * Process the CONNECT command message.
     * 
     * @param message
     *            the command message to be processed.
     */
    public void processCommand(JSONObject message) {
        Integer[] nativeDimensions = receiver.getApplicationConnectionData().getDeviceCaps().getNativeDimensions();
        XREView rootView = new XREView();
        rootView.setId(Config.ROOTVIEW_ID);
        rootView.setKlass(Config.XRE_KLASS_VIEW);
        rootView.setDimensions(new Integer[] { nativeDimensions[0], nativeDimensions[1] });

        // clear resources
        receiver.getApplicationData().setElementsXREIdToElement(new HashMap<Integer, XREObject>());
        receiver.getApplicationData().getElementsXREIdToElement().put(rootView.getId(), rootView);

        XREApplication application = new XREApplication();
        application.setId(Config.APPLICATION_ID);
        application.setMinimumVersion(Config.MINIMUM_VERSION);
        application.setUri("xre://" + receiver.getApplicationConnectionData().getHost() + ":"
                + receiver.getApplicationConnectionData().getPort() + "/"
                + receiver.getApplicationConnectionData().getApplicationName());
        receiver.getApplicationData().getElementsXREIdToElement().put(application.getId(), application);

        // update the whole layout view
        Handler refreshHandler = receiver.getApplicationData().getLayoutRefreshHandler();
        refreshHandler.sendMessage(refreshHandler.obtainMessage());
    }
}
